<?php
require(CP_PATH . 'lib/common.function.php');
require(CP_PATH . 'ext/template_ext.php');

//调试运行时间和占用内存
function debug($flag='system', $end = false){
	static $arr =array();
	if( !$end ){
		$arr[$flag] = microtime(true); 
	} else if( $end && isset($arr[$flag]) ) {
		echo  '<p>' . $flag . ': runtime:' . round( (microtime(true) - $arr[$flag]), 6)
			 . '	memory_usage:' . memory_get_usage()/1000 . 'KB</p>'; 
	}
}

//保存配置
function save_config($app, $new_config = array()){
	if( !is_file($app) ){
		$file = BASE_PATH . 'apps/' . $app. '/config.php';
	}else{
		$file = $app;
	}
	
	if( is_file($file) ) {
		$config = require($file);
		$config = array_merge($config, $new_config);
	}else{
		$config = $new_config;
	}
	$content = var_export($config, true);
	$content = str_replace("_PATH' => '" . addslashes(BASE_PATH), "_PATH' => BASE_PATH . '", $content);

	if( file_put_contents($file, "<?php \r\nreturn " . $content . ';' ) ) {
		return true;
	}
	return false;
}

function copy_dir($src, $dst, $del = false) {
	if ($del && file_exists($dst)){
		return del_dir($dst);
	}
	if (is_dir($src)) {
		@mkdir($dst, 0777, true);
		$files = scandir($src);
		foreach ($files as $file){
			if ($file != "." && $file != "..") copy_dir("$src/$file", "$dst/$file");
		}
	}
	else if (file_exists($src)) copy($src, $dst);
}

//判断ajax提交
function is_ajax() {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') return true;
    if (isset($_POST['ajax']) || isset($_GET['ajax'])) return true;
    return false;
}

//随机字母
function order_sn() {
    $year_code = array('A','B','C','D','E','F','G','H','I','J');
	return $year_code[intval(date('Y'))-2010].
	strtoupper(dechex(date('m'))).date('d').
	substr(time(),-5).substr(microtime(),2,5).sprintf('%02d',rand(0,99));
}

//随机数
function getcode ($length = 5, $mode = 0){
	switch ($mode) {
		case '1':
			$str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';
			break;
		case '2':
			$str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-=[]\',./';
			break;
		case '3':
			$str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ<>?:"|{}_+';
			break;		
		default:
			$str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			break;
	}
	$result = '';
	$l = strlen($str)-1;
	$num=0;

	for($i = 0;$i < $length;$i ++){
	    $num = rand(0, $l);
	    $a=$str[$num];
	    $result =$result.$a;
	}
	return $result;
}

/*截取html字符串*/
function html_explode($content,$maxPerPage){
	$currentContent = "";
	$currentTag = "";
	$currentEntity = "";
	$charCount = 0;
	$pos = 0;
	$state = 0; //0普通文本，1准备进入标签，2标签
	$inEntity = 0; // 0未进实体，1准备进入实体，2在实体中
	$tagsArr = array (); //标签栈
	$pagerContent = array (); //存储分页后内容
	while (($char = mb_substr($content, $pos, 1, "utf-8"))!="") {
	        $pos++;
	        if ($state == 0) {
	                if ($char == "<") {
	                        $state = 1;
	                        continue;
	                } else {
	                        if ($inEntity == 0) {
	                                if ($char == "&") {
	                                        $currentEntity = "&";
	                                        $inEntity = 1;
	                                        continue;
	                                }else{
	                                        $currentContent .= $char;
	                                }
	                        }
	                        elseif ($inEntity == 1) {
	                                if (preg_match_all("#[a-zA-Z\#]#", $char, $matchArr)) {
	                                        $currentEntity.= $char;
	                                        $inEntity = 2;
	                                        continue;
	                                } else // 不是字符实体
	                                        {
	                                        $inEntity = 0;
	                                        if ($charCount +1 == $maxPerPage) {
	                                                $currentContent.= "&";
	                                                $nextContent = "";
	                                                $tempQueue = array ();
	                                                while ($popTag = array_pop($tagsArr)) {
	                                                        $currentContent.= "</$popTag[0]>";
	                                                        $nextContent = "<$popTag[1]>" . $nextContent;
	                                                        array_unshift($tempQueue, $popTag);
	                                                }
	                                                $tagsArr = $tempQueue;
	                                                $pagerContent[] = $currentContent;
	                                                $currentContent = $nextContent . $char;
	                                                $charCount = 1;
	                                                continue;
	                                        }
	                                        elseif ($charCount +2 == $maxPerPage) {
	                                                $currentContent.= "&".$char;
	                                                $nextContent = "";
	                                                $tempQueue = array ();
	                                                while ($popTag = array_pop($tagsArr)) {
	                                                        $currentContent .= "</$popTag[0]>";
	                                                        $nextContent = "<$popTag[1]>" . $nextContent;
	                                                        array_unshift($tempQueue, $popTag);
	                                                }
	                                                $tagsArr = $tempQueue;
	                                                $pagerContent[] = $currentContent;
	                                                $currentContent = $nextContent;
	                                                $charCount = 0;
	                                                continue;
	                                        }
	                                        $charCount += 2;
	                                        $currentContent .= "&" . $char;
	                                }
	                        }
	                        elseif ($inEntity == 2) {
	                                $currentEntity.= $char;
	                                if ($char != ";") {
	                                        continue;
	                                }else{
	                                        $currentContent.= $currentEntity;
	                                        $currentEntity = "";
	                                        $inEntity = 0;
	                                }
	                        }
	                        $charCount++;
	                        if ($charCount == $maxPerPage) {
	                                $charCount = 0;
	                                $nextContent = "";
	                                $tempQueue = array ();
	                                while ($popTag = array_pop($tagsArr)) {
	                                        $currentContent .= "</$popTag[0]>";
	                                        $nextContent = "<$popTag[1]>" . $nextContent;
	                                        array_unshift($tempQueue, $popTag);
	                                }
	                                $tagsArr = $tempQueue;
	                                $pagerContent[] = $currentContent;
	                                $currentContent = $nextContent;
	                        }
	                        continue;
	                }
	        }
	        elseif ($state == 1) {
	                $currentTag = "";
	                if (preg_match_all("#[a-zA-Z!/]#", $char, $matchArr)) { //进入标签
	                        $currentTag = $char;
	                        $state = 2;
	                        continue;
	                } else { //不是标签
	                        if ($charCount +1 == $maxPerPage) {
	                                $currentContent .= "<";
	                                $nextContent = "";
	                                $tempQueue = array ();
	                                while ($popTag = array_pop($tagsArr)) {
	                                        $currentContent .= "</$popTag[0]>";
	                                        $nextContent = "<$popTag[1]>" . $nextContent;
	                                        array_unshift($tempQueue, $popTag);
	                                }
	                                $tagsArr = $tempQueue;
	                                $pagerContent[] = $currentContent;
	                                $currentContent = $nextContent . $char;
	                                $charCount = 1;
	                        }
	                        elseif ($charCount +2 == $maxPerPage) {
	                                $currentContent .= "<" . $char;
	                                $nextContent = "";
	                                $tempQueue = array ();
	                                while ($popTag = array_pop($tagsArr)) {
	                                        $currentContent .= "</$popTag[0]>";
	                                        $nextContent = "<$popTag[1]>" . $nextContent;
	                                        array_unshift($tempQueue, $popTag);
	                                }
	                                $tagsArr = $tempQueue;
	                                $pagerContent[] = $currentContent;
	                                $currentContent = $nextContent;
	                                $charCount = 0;
	                        } else {
	                                $charCount += 2;
	                                $currentContent .= "<" . $char;
	                        }
	                        $state = 0;
	                        continue;
	                }
	        }
	        elseif ($state == 2) {
	                if ($char == ">") { //自关闭不处理, 标签开进栈，标签闭出栈
	                        $currentTag = trim($currentTag);
	                        $currentContent .= "<$currentTag>";
	                        if ($currentTag[strlen($currentTag) - 1] == "/") {
	                        }
	                        elseif ($currentTag {
	                                0 }
	                        != "/") {
	                                $tag = explode(" ", $currentTag);
	                                array_push($tagsArr, array (
	                                        $tag[0],
	                                        $currentTag
	                                ));
	                        } else {
	                                $tag = explode(" ", $currentTag);
	                                $tag = substr($tag[0], 1);
	                                $tempStack = array ();
	                                while ($popTag = array_pop($tagsArr)) {
	                                        if ($popTag[0] == $tag) {
	                                                break;
	                                        } else {
	                                                array_push($tempStack, $popTag);
	                                        }
	                                }
	                                while ($popTag = array_pop($tempStack)) {
	                                        array_push($tagsArr, $popTag);
	                                }
	                        }
	                        $currentTag = "";
	                        $state = 0;
	                        continue;
	                } else {
	                        $currentTag .= $char;
	                        continue;
	                }
	        }
	}
	if ($currentContent!="") {
	        while ($popTag = array_pop($tagsArr)) {
	                $currentContent .= "</$popTag[0]>";
	                $nextContent = "<$popTag[1]>" . $nextContent;
	        }
	        $pagerContent[] = $currentContent;
	}
	return $pagerContent;
}

//设置cookie
function set_cookie($key, $value = '', $dir ,$time = 0) 
{
	$config=config('APP');
	$time = $time > 0 ? $time : 0;
	return setcookie($key, cp_encode($value,$config['SAFE_KEY']), $time, $dir);
}
//获取cookie
function get_cookie($key)
{
	$config=config('APP');
	return isset($_COOKIE[$key]) ? cp_decode($_COOKIE[$key],$config['SAFE_KEY']) : '';
}

//数组排序
function array_order($array,$key,$type='asc'){
	if(empty($array)||!is_array($array)){
		return $array;
	}
	foreach ($array as $k => $v) {
        $keysvalue[$k] = $v[$key];
    }
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    foreach ($keysvalue as $k=>$v){
    	$new_array[$k] = $array[$k];
    }
    return $new_array;

}

//清除html
function clear_html($string)    
{
	$string = strip_tags($string);
	$string = preg_replace ('/\n/is', '', $string);
	$string = preg_replace ('/ |　/is', '', $string);
	$string = preg_replace ('/&nbsp;/is', '', $string);
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $t_string);   
	$string = join('', $t_string[0]);
	return $string;
}

//HOOK合并排序
function hook_merge($list)
{

	$menu_list=array();
	if(!empty($list)){
		foreach ($list as $appname => $url_info) {
			$menu_list=array_merge((array)$menu_list,(array)$url_info);
		}
	}
	return array_order($menu_list,'sequence','asc');
}